package com.food.foodapi;

import com.food.foodapi.exception.AuthenticationException;
import com.food.foodapi.instans.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice(basePackages = "com.food.foodapi")
public class GlobalExceptionHandler {

    // 捕获自定义的 AuthenticationException 异常
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<ErrorResponse> handleAuthenticationException(AuthenticationException ex) {
        // 创建一个统一格式的错误响应
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(ex.getMessage());
        errorResponse.setStatus(ex.getStatusCode());

        // 返回错误信息和状态码
        return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(ex.getStatusCode()));
    }


    // 你还可以添加其他异常处理方法，比如处理 Token 为空的情况
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<?> handleNullPointerException(NullPointerException ex) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage("发生了空指针异常");
        errorResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());

        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
